home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 10717 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: news.umbc.edu!not-for-mail
  2. From: schlein@umbc.edu (Jonas J. Schlein)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Empty String function
  5. Date: 19 Mar 1996 11:00:25 -0500
  6. Organization: University of Maryland Baltimore County
  7. Message-ID: <4imlmp$j4q@umbc9.umbc.edu>
  8. References: <1996Mar14.205741.19178@vtf.idx.com>
  9. NNTP-Posting-Host: umbc9.umbc.edu
  10. NNTP-Posting-User: schlein
  11.  
  12. Steve Mount  <sjjm@hawkeye.idx.com> wrote:
  13. |> I benchmarked several methods for testing a buffer's 
  14. |> emptiness.  Empty is defined as all characters being space,
  15. |> newline, or tab.  I hit on one very fast method; it
  16. |> blew the others out of the water.  I presume the standard
  17. |> function I'm using is optimized.  But it has a potential
  18. |> problem I'm concerned about - can anyone tell me if it 
  19. |> could be illegal, or at the least, bad form? 
  20. |> Here it is:
  21. |> 
  22. |> int zemp(char *ptxt, int len)
  23. |> {
  24. |> static int i;
  25. |> 
  26. |> if (len == 0) len = strlen(ptxt);  // Allow null-term strings
  27. |> i = strspn(ptxt," \n\t");
  28. |> if (i >= len) return(-1);          // -1 == EMPTY
  29. |> return(i);
  30. |> }
  31.  
  32. Well you have used C++ comments which are not supported by ANSI C compilers
  33. which are compliant with the standard. Also defining 'i' as static doesn't
  34. seem to do much except cause sizeof(int) to be permanently allocated
  35. to the zemp() function. I guess if you call this function a lot then
  36. maybe it could help.
  37.  
  38. |> The problem is when the buffer is not null-terminated, which
  39. |> happens a lot.  The strspn function COULD read past the end
  40. |> of the buffer.... potentially WAY past it.  Possibly even into
  41. |> memory not owned by the program.  This is where I get concerned.
  42.  
  43. I would be concerned as well. The C library <string.h> is written with
  44. NUL (not null as you wrote) terminated strings in mind. From your code
  45. we cannot even be sure if you #included this. If you desire some other
  46. definition of a string you will need to write your own functions from
  47. scratch.
  48.  
  49. |> Anyone know if this could cause trouble, generally, and if
  50. |> it could cause trouble specifically in DOS/Win/Unix (it is
  51. |> used in a Unix app now).
  52.  
  53. Accessing memory past an array's upper limit is illegal on any platform.
  54. Some compilers may be smarter at detecting this at compile time, but
  55. none are required to.
  56. -- 
  57. "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
  58.  
  59. Jonas J. Schlein  (schlein@gl.umbc.edu)
  60.